package com.kexun.lxj;


/*关于静态的方法*/
public class Demo04 {
    public static void main(String[] args) {
        Runnable r =new Ticket5();

        //创建四个线程,卖同一个资源
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        Thread t3 = new Thread(r);
        Thread t4= new Thread(r);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }


}
class Ticket5 implements Runnable {

    private static int i = 20;

    @Override
    public void run() {
        while (true) {

             sellTicket2();

            if(i==0){
                break;
            }
        }
    }


    //静态方法的锁对象是谁呢？

    //静态方法加载时还没有对象       锁对象是字节码文件
    public static synchronized void sellTicket() {
        if (i > 0) {
            try {
                System.out.println("这是" + Thread.currentThread().getName() + "卖出的第" + i-- + "张票");
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println(Thread.currentThread().getName() + "卖完了,关闭卖票窗口");

        }
    }

    public static  void sellTicket2() {
        synchronized(Ticket5.class){
            if (i > 0) {
                try {
                    System.out.println("这是" + Thread.currentThread().getName() + "卖出的第" + i-- + "张票");
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "卖完了,关闭卖票窗口");

            }
        }

    }

}